#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSharedMemory>
#include <QFileDialog>
#include <QPixmap>
#include <QBuffer>
#include <QDebug>

const char* KEY_SHARED_MEMORY = "Shared";

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    sharedMemory(new QSharedMemory(KEY_SHARED_MEMORY, this))
{
    ui->setupUi(this);
    connect(ui->loadButton, SIGNAL(clicked()),SLOT(OnClickLoadButton()));
    connect(ui->saveButton, SIGNAL(clicked()),SLOT(OnClickSaveButton()));
}

MainWindow::~MainWindow()
{
    delete ui;
    delete  sharedMemory;
}

void MainWindow::OnClickLoadButton()
{
    if (!sharedMemory->attach())
    {
        qDebug() << tr("Attach Error: ") << sharedMemory->errorString();
    }
    else
    {
        QBuffer buffer;
        QDataStream in(&buffer);
        QPixmap pixmap;
        sharedMemory->lock();
        buffer.setData(static_cast<const char *>(sharedMemory->constData()), sharedMemory->size());
        buffer.open(QBuffer::ReadWrite);
        in >> pixmap;
        sharedMemory->unlock();
        sharedMemory->detach();
        ui->label->setPixmap(pixmap);
    }
}

void MainWindow::OnClickSaveButton()
{

    if (sharedMemory->isAttached())
    {
        sharedMemory->detach();
    }

    QString filename = QFileDialog::getOpenFileName(this);
    QPixmap pixmap(filename);
    ui->picLabel->setPixmap(pixmap);

    QBuffer buffer;
    QDataStream out(&buffer);
    buffer.open(QBuffer::ReadWrite);
    out << pixmap;
    int32_t size = buffer.size();
    if (!sharedMemory->create(size)) {
        qDebug() << tr("Create Error: ") << sharedMemory->errorString();
    }
    else
    {
        sharedMemory->lock();
        char *to = static_cast<char *>(sharedMemory->data());
        const char *from = buffer.data().constData();
        memcpy(to, from, qMin(size, sharedMemory->size()));
        sharedMemory->unlock();
    }

}
